<template class="body">
  <div class="main">
    <div class="marketplace">
      <div class="summary">市场任务数量 {{ preparedTaskList.length }}</div>
      <div v-for="(taskGroup, index) in preparedTaskList" :key="index" class="task-group">
        <div> #{{ taskGroup.code }} {{ taskGroup.subject }} </div>
        <div>
          <span class="column">发布时间</span> <span class="value">{{ taskGroup.gmtWrite }}</span>
        </div>
        <div>
          <span class="column">期望完成时间</span> <span class="value">{{ taskGroup.gmtExpectFinish }}</span> <span class="column">备注</span> <span class="value">{{ taskGroup.creatorRemarks }}</span>
        </div>
        <div>
          <span class="column">发起人</span> <span class="value">{{ taskGroup.creatorUserName }}</span>
        </div>
        <div>
          <span class="column">类型</span> <span class="value">{{ taskGroup.type }}</span>
        </div>
        <div style="margin-bottom: 5px">
          <div><span class="column-name">认领</span></div>
          <div>
            <a-select size="mini" :style="{ width: '120px' }" placeholder="select ..." v-model="taskGroup.nextPerson">
              <a-option v-for="(member, member_index) in members" :key="member_index" :value="member.userId" :label="member.name"></a-option>
            </a-select>
            <a-button type="outline" size="mini" status="success" style="margin-top: 5px" @click="onAcceptByLeader(taskGroup)"> 确认分配</a-button>
          </div>
        </div>
        <div>
          <a-tag style="margin-right: 5px; margin-bottom: 5px" color="#ff5722" v-for="(task, task_index) in taskGroup.tasks" :key="task_index"
            >{{ task.subject }}
            <span class="pricetag" v-if="task.budgetPrice">价格:{{ task.budgetPrice }}</span>
          </a-tag>
        </div>
      </div>
    </div>
    <div class="teams">
      <div class="team-task" v-for="(member, index) in teams" :key="index">
        <div style="font-size: 15px"
          ><span style="font-weight: bold">{{ member.name }}</span> 进行中 {{ member.inprocessTaskList.length }} 待排期 {{ member.acceptedTaskList.length }}
        </div>
        <div v-for="(taskGroup, index1) in member.inprocessTaskList" :key="index1" class="task-group task-group-inprocess">
          <div> #{{ taskGroup.code }} {{ taskGroup.subject }} </div>

          <div v-if="taskGroup.scoreRemarks">
            <span class="column">置顶</span> <span class="important-things">{{ taskGroup.scoreRemarks }}</span>
          </div>

          <div>
            <span class="column">发布时间</span> <span class="value">{{ taskGroup.gmtWrite }}</span>
          </div>
          <div>
            <span class="column">期望完成时间</span> <span class="value">{{ taskGroup.gmtExpectFinish }}</span> <span class="column">备注</span> <span class="value">{{ taskGroup.creatorRemarks }}</span>
          </div>

          <div>
            <span class="column">发起人</span> <span class="value">{{ taskGroup.creatorUserName }}</span>
          </div>
          <div>
            <span class="column">类型</span> <span class="value">{{ taskGroup.type }}</span>
          </div>
          <div>
            <div>
              <a-button v-if="index1 > 0" type="text" size="mini" status="normal" style="margin-top: 5px; margin-bottom: 5px" @click="onShowSetTopDialog(member, taskGroup)"> 置顶↑ </a-button>
            </div>
          </div>

          <div>
            <a-button type="outline" style="margin-bottom: 3px" size="mini" v-for="(task, task_index) in taskGroup.tasks" :key="task_index">{{ task.subject }}</a-button>
          </div>
        </div>
        <div v-for="(taskGroup, index2) in member.acceptedTaskList" :key="index2" class="task-group task-group-accepted">
          <div> #{{ taskGroup.code }} {{ taskGroup.subject }} </div>
          <div>
            <span class="column">发布时间</span> <span class="value">{{ taskGroup.gmtWrite }}</span>
          </div>
          <div>
            <span class="column">期望完成时间</span> <span class="value">{{ taskGroup.gmtExpectFinish }}</span> <span class="column">备注</span> <span class="value">{{ taskGroup.creatorRemarks }}</span>
          </div>
          <div>
            <span class="column">发起人</span> <span class="value">{{ taskGroup.creatorUserName }}</span>
          </div>
          <div>
            <span class="column">类型</span> <span class="value">{{ taskGroup.type }}</span>
          </div>
          <div>
            <div>
              <a-button v-if="index2 > 0" type="text" size="mini" status="normal" style="margin-top: 5px; margin-bottom: 5px" @click="onShowSetTopDialog(member, taskGroup)"> 置顶↑ </a-button>
              <a-button type="text" size="mini" status="normal" style="margin-top: 5px; margin-bottom: 5px" @click="onStartByLeader(member, taskGroup)"> 开始 </a-button>
            </div>
          </div>
          <div style="margin-bottom: 20px">
            <div><span class="column-name">转给其它人</span></div>
            <div>
              <a-select size="mini" :style="{ width: '200px' }" placeholder="Please select ..." v-model="taskGroup.nextPerson">
                <a-option v-for="(member, member_index) in members" :key="member_index" :value="member.userId" :label="member.name"></a-option>
              </a-select>
              <a-button type="outline" size="mini" status="success" style="margin-top: 5px" @click="onTaskTransfer(member, taskGroup)"> 确认转交</a-button>
            </div>
          </div>

          <div>
            <a-tag style="margin-right: 5px; margin-bottom: 5px" color="#86909c" v-for="(task, task_index) in taskGroup.tasks" :key="task_index"
              >{{ task.subject }}
              <span class="pricetag" v-if="task.budgetPrice">价格:{{ task.budgetPrice }}</span>
            </a-tag>
          </div>
        </div>
      </div>
    </div>

    <a-modal v-model:visible="dialogSetToTop.visible" @ok="onSetToTop(dialogSetToTop.member, dialogSetToTop.taskGroup)">
      <template #title> 置顶 </template>
      <div>
        如果重要的事情，请输入留言，这样方便执行人可以更及时的完成您的任务！
        <a-input :style="{ width: '320px' }" v-model="dialogSetToTop.scoreRemarks" placeholder="置顶留言" size="medium" allow-clear />
      </div>
      <div style="margin-top: 5px"><a-switch size="small" v-model="dialogSetToTop.needStart" /> &nbsp;是否要马上开始该任务?</div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { preparedTaskGroupSearchV2, acceptByLeader, startTask, hangupTask, updateTaskResult, findTeamTasks, setTaskGroupScore, startByLeader, findTeamMember, transferByLeader } from '@/api/task'
import { Message } from '@arco-design/web-vue'
let teams: any = ref([])
let preparedTaskList: any = ref([])
let dialogSetToTop: any = ref({ visible: false, taskGroup: null, member: null, scoreRemarks: null, needStart: true })
let members: any = ref([])
/**
 * Load Team's Task
 */
const onTeamTaskLoad = async () => {
  let rs = await findTeamTasks({ statusList: ['accepted', 'in-process', 'hang-up'] })
  //let userIdList = [...new Set((rs?.data?.records || []).map((item: any) => item.executeUserId))]
  //alert(JSON.stringify(userIdList))
  let map: any = {}
  ;(rs?.data?.records || []).forEach((item: any) => {
    if (!map[item.executeUserId]) {
      map[item.executeUserId] = {
        name: item.executeUserName,
        userId: item.executeUserId,
        acceptedTaskList: [],
        inprocessTaskList: [],
      }
    }
    if (item.status === 'in-process') {
      map[item.executeUserId].inprocessTaskList.push(item)
    } else if (item.status === 'accepted' || item.status === 'hang-up') {
      map[item.executeUserId].acceptedTaskList.push(item)
    }
  })
  Object.keys(map).forEach((key) => {
    teams.value.push(map[key])
  })
  teamTaskSort()
}
/**
 * Leader can start task for member
 *
 */

const onStartByLeader = async (member: any, taskGroup: any) => {
  let rs = await startByLeader({ taskGroupIdList: [taskGroup.id] })
  Message.success('已加入排队')

  member.acceptedTaskList.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      member.acceptedTaskList.splice(index, 1)
    }
  })
  member.inprocessTaskList.push(taskGroup)
  teamTaskSort()
}
/**
 * sort for task list
 */
const teamTaskSort = () => {
  teams.value.forEach((member: any) => {
    member.acceptedTaskList = member.acceptedTaskList.sort((a: any, b: any) => a.score < b.score)
    member.inprocessTaskList = member.inprocessTaskList.sort((a: any, b: any) => a.score < b.score)
  })
}
/**
 * On set to Top
 */
const onShowSetTopDialog = (member: any, taskGroup: any) => {
  dialogSetToTop.value.member = member
  dialogSetToTop.value.taskGroup = taskGroup
  if (taskGroup.status === 'in-process') {
    dialogSetToTop.value.needStart = false
  } else {
    dialogSetToTop.value.needStart = true
  }
  dialogSetToTop.value.visible = true
}
const onSetToTop = async (member: any, taskGroup: any) => {
  let v = new Date().getTime()
  let rs = await setTaskGroupScore({ scores: [{ taskGroupId: dialogSetToTop.value.taskGroup.id, score: v, scoreRemarks: dialogSetToTop.value.scoreRemarks }] })
  if (dialogSetToTop.value.scoreRemarks) {
    taskGroup.scoreRemarks = dialogSetToTop.value.scoreRemarks
  }
  dialogSetToTop.value.taskGroup.score = v
  if (dialogSetToTop.value.needStart) {
    await onStartByLeader(dialogSetToTop.value.member, dialogSetToTop.value.taskGroup)
  }
  teamTaskSort()
}
const onFindTeamMember = async () => {
  let rs = await findTeamMember()
  members.value = rs?.data?.members
}

const onAcceptByLeader = async (taskGroup: any) => {
  let rs = await acceptByLeader({ taskGroupIdList: [taskGroup.id], executeUserId: taskGroup.nextPerson })

  preparedTaskList.value.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      preparedTaskList.value.splice(index, 1)
    }
  })
}

const onTaskTransfer = async (member: any, taskGroup: any) => {
  let rs = await transferByLeader({ taskGroupIdList: [taskGroup.id], executeUserId: taskGroup.nextPerson })
  member.acceptedTaskList.forEach((item: any, index: any) => {
    if (item.id === taskGroup.id) {
      member.acceptedTaskList.splice(index, 1)
    }
  })
  Message.success('转交成功')
}
onMounted(async () => {
  let result = await preparedTaskGroupSearchV2({})
  preparedTaskList.value = result?.data?.records || []
  await onTeamTaskLoad()
  await onFindTeamMember()
})
</script>

<style lang="less" scoped>
.main {
  display: flex;
  min-height: 500px;
  height: 100%;
  overflow-y: scroll;
  .task-group {
    font-size: 12px;
    min-height: 100px;
    margin: 10px;
    padding: 5px;
    border-radius: 5px;
    border: 1px solid gray;
    .column {
      font-weight: bold;
    }
    .value {
      color: gray;
    }
  }
  .task-group-inprocess {
    border: 2px solid green;
  }
  .task-group-accepted {
    border: 2px solid gray;
  }
  .marketplace {
    width: 300px;
    border-right: 1px dashed red;
    .summary {
      margin-left: 20px;
      font-size: 20px;
    }
  }
  .teams {
    flex-grow: 1;
    display: flex;
    .team-task {
      min-width: 200px;
      max-width: 300px;
      margin-right: 5px;
      border-right: 1px dashed green;
      margin-left: 5px;
    }
  }
  .important-things {
    color: red !important;
  }
  .pricetag {
    margin-left: 5px;
  }
}
</style>